package com.tencent.iov.cowin.befsale.clue.service.cus.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.google.common.collect.Lists;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.response.ClueTaskDataHistory;
import com.tencent.iov.cowin.befsale.clue.controller.cus.assembler.OemCustomerFollowRecordAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.request.AddCustomerFollowRecordRequest;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.request.ClueIntentionGradeDataRequest;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.request.QueryCustomerFollowPlanRequest;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.response.CustomerFollowPlanResponse;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.response.CustomerFollowRecordResponse;
import com.tencent.iov.cowin.befsale.clue.domain.cus.po.OemCustomerFollowPlan;
import com.tencent.iov.cowin.befsale.clue.domain.cus.po.OemCustomerFollowRecord;
import com.tencent.iov.cowin.befsale.clue.domain.cus.vo.CustomerBehaviorStatistical;
import com.tencent.iov.cowin.befsale.clue.repository.cus.OemCustomerFollowRecordManager;
import com.tencent.iov.cowin.befsale.clue.service.clue.ClueFailService;
import com.tencent.iov.cowin.befsale.clue.service.clue.ClueOrderService;
import com.tencent.iov.cowin.befsale.clue.service.cus.OemCustomerFollowPlanService;
import com.tencent.iov.cowin.befsale.clue.service.cus.OemCustomerFollowRecordService;
import com.tencent.iov.cowin.befsale.clue.value.enums.ExpireStatusEnum;
import com.tencent.iov.cowin.befsale.clue.value.enums.FollowPlanStatusEnum;
import com.tencent.iov.cowin.befsale.clue.value.enums.FollowRecordSecondStatusEnum;
import com.tencent.iov.cowin.befsale.clue.value.enums.FollowRecordStatusEnum;
import com.software.boot.common.exception.BusinessException;
import com.software.boot.common.exception.NEError;
import com.software.boot.common.model.dao.OrderField;
import com.software.boot.common.model.dao.PageRequest;
import com.software.boot.common.model.dao.PageResponse;
import com.software.boot.common.util.BeanUtil;
import com.software.boot.common.util.DateUtil;
import com.software.boot.common.util.EmptyUtils;
import com.software.boot.common.util.ValidateUtils;
import com.software.common.enums.DeleteEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Describe: 总部线索跟进记录_Service实现层
 * @author: xiamu
 * @created: 2021-12-21 18:37:32
 * @version: 1.0
 */
@Service
@Slf4j
public class OemCustomerFollowRecordServiceImpl implements OemCustomerFollowRecordService {

    @Autowired
    private OemCustomerFollowRecordManager oemCustomerFollowRecordManager;
    @Autowired
    private OemCustomerFollowPlanService oemCustomerFollowPlanService;
    @Autowired
    private ClueOrderService clueOrderService;
    @Autowired
    private ClueFailService clueFailService;

    /**
     * 通过ID获取详细信息
     *
     * @param: request
     * @return: OemCustomerFollowRecord对象
     */
    @Override
    public OemCustomerFollowRecord getDetailById(Long id) {
        /** 1 验证请求参数 */
        ValidateUtils.checkObjNull(id, "请求参数不能为空");
        ValidateUtils.checkIntNotNullAndGTZero(id.intValue(), "ID不能为空或小于0");
        /** 2 处理业务 */
        OemCustomerFollowRecord oemCustomerFollowRecord = oemCustomerFollowRecordManager.getDetailById(id);
        if (EmptyUtils.isNotEmpty(oemCustomerFollowRecord)) {
            return BeanUtil.copy(oemCustomerFollowRecord, OemCustomerFollowRecord.class);
        }
        /** 3 返回结果 */
        return null;
    }

    @Override
    public Long insert(AddCustomerFollowRecordRequest request) {
        //验证请求参数
        ValidateUtils.checkObjNull(request, "参数为null");
        ValidateUtils.checkLongGTZero(request.getClueId(), "线索Id不可以为null");
        ValidateUtils.checkLongGTZero(request.getCusId(), "总部客户ID不可以为null");

        request = OemCustomerFollowRecordAssembler.initAddOemCustomerFollowRecordRequest(request);
        //处理业务
        OemCustomerFollowRecord followRecord = OemCustomerFollowRecordAssembler.transformPOToResponseVo(request, OemCustomerFollowRecord.class);

        //填充跟进逾期信息与更新上次跟进计划为完成
        fillExpireInfoAndUpdateFollowPlan(followRecord,request);

        int count = oemCustomerFollowRecordManager.insert(followRecord);
        if (count <= 0) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "保存总部客户跟进记录失败");
        }
        //封装返回值
        return followRecord.getId();
    }



    private void fillExpireInfoAndUpdateFollowPlan(OemCustomerFollowRecord followRecord,AddCustomerFollowRecordRequest request) {
        //处理时间
        Date operateTime = EmptyUtils.isEmpty(followRecord.getOperateTime()) ? new Date() : followRecord.getOperateTime();
        request.setOperateTime(operateTime);
        followRecord.setOperateTime(operateTime);
        followRecord.setExpireStatus(ExpireStatusEnum.EXPIRY_IN.getCode());
        followRecord.setExpireTime(0L);

        if (EmptyUtils.isEmpty(followRecord.getSecondStatus()) || !FollowRecordSecondStatusEnum.checkFollowExpire(followRecord.getSecondStatus())) {
            return;
        }

        CustomerFollowPlanResponse followPlan;
        //获取跟进计划
        if (EmptyUtils.isEmpty(followRecord.getFollowPlanId()) || followRecord.getFollowPlanId() <= 0) {
            //获取最近一次未完成跟进计划，计算跟进时间
            QueryCustomerFollowPlanRequest queryRequest = new QueryCustomerFollowPlanRequest();
            queryRequest.setStatus(FollowPlanStatusEnum.WAIT_FOLLOW.getCode());
            queryRequest.setClueId(followRecord.getClueId());
            queryRequest.setOrderFields(Lists.newArrayList(new OrderField("id", "DESC")));
            followPlan = oemCustomerFollowPlanService.getOneByParam(queryRequest);
        } else {
            followPlan = oemCustomerFollowPlanService.getDetailById(followRecord.getFollowPlanId());
        }

        if (EmptyUtils.isEmpty(followPlan) || EmptyUtils.isEmpty(followPlan.getStatus())
                || FollowPlanStatusEnum.FINISH_FOLLOW.getCode().equals(followPlan.getStatus())) {
            log.info("[DealerCustomerFollowRecordService][fillExpireInfoAndUpdateFollowPlan] 计划跟进不满足条件 followPlan={}",
                    EmptyUtils.isEmpty(followPlan) ? null : JSON.toJSONString(followPlan));
            return;
        }

        //计划跟进为本次记录的下次跟进 不做更新与计算延期状态
        if (followPlan.getId().equals(followRecord.getNextFollowPlanId())) {
            return;
        }

        followRecord.setFollowPlanId(followPlan.getId());

        //填充跟进记录延期信息
        fillExpireInfo(followRecord, followPlan);

        //分配跟进人不做跟进计划操作
        if (FollowRecordSecondStatusEnum.DISTRIBUTION.getCode().equals(followRecord.getSecondStatus())) {
            return;
        }

        OemCustomerFollowPlan updateRequest = new OemCustomerFollowPlan();
        updateRequest.setId(followPlan.getId());
        updateRequest.setStatus(FollowPlanStatusEnum.FINISH_FOLLOW.getCode());
        int updateFollowPlanResult = oemCustomerFollowPlanService.update(updateRequest);
        if (updateFollowPlanResult <= 0) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "更新经销商跟进计划信息失败");
        }
    }

    /**
     * 计算跟进记录的过期时间
     * @param followRecord 跟进记录
     * @param followPlan 计划跟进
     */
    private void fillExpireInfo(OemCustomerFollowRecord followRecord, CustomerFollowPlanResponse followPlan) {
        Date operateTime = followRecord.getOperateTime();
        //未逾期
        if (EmptyUtils.isEmpty(followPlan.getPlanFollowTime()) || operateTime.before(followPlan.getPlanFollowTime())) {
            return;
        }

        //设置逾期状态 计算逾期时间
        followRecord.setExpireStatus(ExpireStatusEnum.EXPIRY_OUT.getCode());
        followRecord.setExpireTime((DateUtil.getMillis(operateTime) - DateUtil.getMillis(followPlan.getPlanFollowTime())) / 3600000);

        //判断是否是首次逾期 首次逾期概念-分类1中为跟进的 即 status-> 跟进中的
        if (!FollowRecordStatusEnum.FOLLOW_UP.getCode().equals(followRecord.getStatus())) {
            return;
        }
        OemCustomerFollowRecord request = new OemCustomerFollowRecord();
        request.setDeleted(DeleteEnum.INIT.getFlag());
        request.setStatus(FollowRecordStatusEnum.FOLLOW_UP.getCode());
        request.setClueId(followRecord.getClueId());
        List<OemCustomerFollowRecord> customerFollowRecords = oemCustomerFollowRecordManager.getListByParam(request);
        if (EmptyUtils.isEmpty(customerFollowRecords)) {
            followRecord.setExpireStatus(ExpireStatusEnum.EXPIRY_OUT_FIRST.getCode());
        }
    }


    @Override
    public int insertBatch(List<AddCustomerFollowRecordRequest> requests) {
        //校验参数
        ValidateUtils.checkObjNull(requests, "请求参数为null");
        //处理业务
        List<OemCustomerFollowRecord> records = BeanUtil.copyByList(requests, OemCustomerFollowRecord.class);
        return oemCustomerFollowRecordManager.insertBatch(records);
    }


    /**
     * 单条OemCustomerFollowRecord更新
     *
     * @param request
     * @return 更新的条数
     */
    @Override
    public int update(OemCustomerFollowRecord request) {

        /** 1 验证请求参数 */
        /** 2 处理业务 */
        int count = oemCustomerFollowRecordManager.update(request);
        /** 3 返回对象 */
        return count;
    }

    /**
     * 通过ID删除数据
     *
     * @param request
     * @return 删除的条数
     */
    @Override
    public int delete(OemCustomerFollowRecord request) {
        Long id = request.getId();
        /** 1 验证请求参数 */
        ValidateUtils.checkObjNull(id, "请求参数不能为空");
        ValidateUtils.checkIntNotNullAndGTZero(id.intValue(), "ID不能为空或小于0");
        /** 2 处理业务 */
        OemCustomerFollowRecord oemCustomerFollowRecord = new OemCustomerFollowRecord();
        oemCustomerFollowRecord.setId(id);
//		oemCustomerFollowRecord.setDelete(DeleteEnum.DETELED.getCode());
        int count = oemCustomerFollowRecordManager.update(oemCustomerFollowRecord);
        /** 3 返回对象 */
        return count;
    }

    @Override
    public List<CustomerFollowRecordResponse> getListByParam(OemCustomerFollowRecord request) {
        //验证请求参数
        ValidateUtils.checkObjNull(request, "参数为null");

        //处理业务
        List<OemCustomerFollowRecord> queryList = oemCustomerFollowRecordManager.getListByParam(request);
        List<CustomerFollowRecordResponse> followRecordResponses = BeanUtil.copyByList(queryList, CustomerFollowRecordResponse.class);
        //返回结果
        if (CollectionUtils.isEmpty(followRecordResponses)) {
            return Lists.newArrayList();
        }
        followRecordResponses.forEach(followRecordResponse -> {
            fillFollowRecordExtInfo(followRecordResponse);
        });
        return followRecordResponses;
    }

    private void fillFollowRecordExtInfo(CustomerFollowRecordResponse followRecordResponse) {
        //战败信息
        if (EmptyUtils.isNotEmpty(followRecordResponse.getFailId()) && followRecordResponse.getFailId() > 0) {
            followRecordResponse.setClueFail(clueFailService.getDetailById(followRecordResponse.getFailId()));
        }
        //下定 订单信息
        if (EmptyUtils.isNotEmpty(followRecordResponse.getOrderId()) && followRecordResponse.getOrderId() > 0) {
            followRecordResponse.setClueOrder(clueOrderService.getDetailById(followRecordResponse.getOrderId()));
        }
    }

    /**
     * 根据条件查询对象list记录
     *
     * @param request
     * @return 分页对象
     */
    @Override
    public PageResponse<OemCustomerFollowRecord> getPageByParam(PageRequest<OemCustomerFollowRecord> request) {
        /** 1 验证请求参数 */
        ValidateUtils.checkObjNull(request, "请求参数不能为空");
        //可以设置排序 query.orderByCreatedTime(true);
        /** 2 处理业务 */
        RowBounds rowBounds = new RowBounds(request.getPageNum(), request.getPageSize());
        Page<OemCustomerFollowRecord> queryPageList = oemCustomerFollowRecordManager.getPageByParam(request.getParamData(), rowBounds);
        PageResponse<OemCustomerFollowRecord> pageResponse = new PageResponse<>();
        pageResponse.converPageResponse(pageResponse, queryPageList, request);
        pageResponse.setDataList(BeanUtil.copyByList(queryPageList.getResult(), OemCustomerFollowRecord.class));
        /** 3 返回结果 */
        return pageResponse;
    }

    @Override
    public CustomerFollowRecordResponse getOneByParam(OemCustomerFollowRecord request) {
        OemCustomerFollowRecord followRecord = oemCustomerFollowRecordManager.getOneByParam(request);
        if (EmptyUtils.isEmpty(followRecord)) {
            return null;
        }
        CustomerFollowRecordResponse followRecordResponse = BeanUtil.copy(followRecord, CustomerFollowRecordResponse.class);
        fillFollowRecordExtInfo(followRecordResponse);
        return followRecordResponse;
    }

    @Override
    public List<CustomerBehaviorStatistical> statisticalByStatus(Date startDate, Date endDate, List<Integer> statues) {
        ValidateUtils.checkObjNull(startDate, "开始时间不可以为null");
        ValidateUtils.checkObjNull(endDate, "结束时间不可以为null");
        return oemCustomerFollowRecordManager.statisticalByStatus(startDate, endDate, statues);
    }

    @Override
    public List<CustomerBehaviorStatistical> statisticalBySecondStatus(Date startDate, Date endDate, List<Integer> secondStatues) {
        ValidateUtils.checkObjNull(startDate, "开始时间不可以为null");
        ValidateUtils.checkObjNull(endDate, "结束时间不可以为null");
        return oemCustomerFollowRecordManager.statisticalBySecondStatus(startDate, endDate, secondStatues);
    }

    /**
     * 根据状态统计记录表
     * add by zly
     *
     * @param clueIntentionGradeDataRequest
     * @return
     */
    @Override
    public Integer getRecordFollowUpData(ClueIntentionGradeDataRequest clueIntentionGradeDataRequest) {
        return oemCustomerFollowRecordManager.getRecordFollowUpData(clueIntentionGradeDataRequest);
    }

    /**
     * 以月份分组，查询月份对应的逾期数量
     * add by zly
     *
     * @param clueIntentionGradeDataRequest
     * @return
     */
    @Override
    public List<ClueTaskDataHistory> getRecordFollowUpHistoryData(ClueIntentionGradeDataRequest clueIntentionGradeDataRequest) {
        return oemCustomerFollowRecordManager.getRecordFollowUpHistoryData(clueIntentionGradeDataRequest);
    }
}
